﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace CGM
{
	public partial class MainForm : Form
	{
		public MainForm()
		{
			InitializeComponent();

			m_lstDataItems = new List<DataItem>();
		}

		// create a new data item
		private void NewDataItem(DataItem _DataItem)
		{
			// add the data to the list
			m_lstDataItems.Add(_DataItem);

			// create a tab page for the texture
			DataItemTabPage page = new DataItemTabPage(_DataItem);
			MainTabView.TabPages.Add(page);

			// create a tree view for the texture
			DataItemTreeNode node = new DataItemTreeNode(_DataItem);
			MainTreeView.Nodes.Add(node);
		}

		// open a data item
		private void OpenDataItem(DataItem _DataItem)
		{
			// let the user choose a file to open
			OpenFileDialog ofd = new OpenFileDialog();
			ofd.Filter = _DataItem.FileFilter;
			if (ofd.ShowDialog() == DialogResult.OK)
			{
				// open the file
				if (_DataItem.Open(ofd.FileName))
				{
					// add the data to the list
					m_lstDataItems.Add(_DataItem);

					// create a tab page for the texture
					DataItemTabPage page = new DataItemTabPage(_DataItem);
					MainTabView.TabPages.Add(page);

					// create a tree view for the texture
					DataItemTreeNode node = new DataItemTreeNode(_DataItem);
					MainTreeView.Nodes.Add(node);
				}
			}
		}

		/////////////////////////////////////////////////////////////////////////////
		// Main Menu

		private void MainMenuFileNewTexture2D_Click(object sender, EventArgs e)
		{
			// create a 2D texture
			NewDataItem(new Texture2DDataItem());
		}

		private void MainMenuFileNewTextureCube_Click(object sender, EventArgs e)
		{
			// create a cube texture
			NewDataItem(new TextureCubeDataItem());
		}

		private void MainMenuFileOpenTexture2D_Click(object sender, EventArgs e)
		{
			// open a 2D texture
			OpenDataItem(new Texture2DDataItem());
		}

		private void MainMenuFileOpenTextureCube_Click(object sender, EventArgs e)
		{
			// open a cube texture
			OpenDataItem(new TextureCubeDataItem());
		}

		private void MainMenuFileSave_Click(object sender, EventArgs e)
		{
			if (MainTabView.SelectedTab != null)
			{
				DataItem data = ((DataItemTabPage)MainTabView.SelectedTab).DataItem;
				if (data.HasFilename)
				{
					data.Save();
				}
				else
				{
					MainMenuFileSaveAs_Click(sender, e);
				}
			}
		}

		private void MainMenuFileSaveAs_Click(object sender, EventArgs e)
		{
			if (MainTabView.SelectedTab != null)
			{
				DataItem data = ((DataItemTabPage)MainTabView.SelectedTab).DataItem;
				SaveFileDialog sfd = new SaveFileDialog();
				sfd.Filter = data.FileFilter;
				if (sfd.ShowDialog() == DialogResult.OK)
				{
					data.SaveAs(sfd.FileName);
				}
			}
		}

		private void MainMenuFileExit_Click(object sender, EventArgs e)
		{
			Close();
		}

		// fields
		private List<DataItem> m_lstDataItems;
	}
}
